<?php
/**
 * licenses : MIT
 * creatTime: 2020/5/15
 * author : weblinuxgame
 * filename: CaptchaService.php
 */

namespace App\Services;

use Redis as RedisClient;
use Illuminate\Support\Facades\Redis;
use Illuminate\Redis\Connections\Connection;

/**
 * Class CaptchaStorageService
 * @package App\Services
 */
class CaptchaStorageService extends BaseService
{
    protected $redis;

    const ExpireTime = 180;
    const ConnectionName = 'code';

    /**
     * @return Connection
     */
    protected function getStore()
    {
        if (empty($this->redis)) {
            $this->redis = Redis::connection(self::ConnectionName);
        }
        return $this->redis;
    }

    /**
     * @return RedisClient
     */
    protected function redis()
    {
        return $this->getStore()->client();
    }

    /**
     *
     * @param string $key
     * @param string $value
     * @param int $expire
     * @return string
     */
    public function store(string $key, string $value, $expire = self::ExpireTime)
    {
        $client = $this->redis();
        if ($client->set($key, $value, $expire)) {
            return $key;
        }
        return '';
    }

    /**
     * 验证是否正确
     * @param $value
     * @param string $key
     * @return bool
     */
    public function verify($value, $key = ''): bool
    {
        if (empty($value)) {
            return false;
        }
        if (empty($key)) {
            $key = request('_xsrf', '');
            if (empty($key)) {
                return false;
            }
        }
        $val = $this->redis()->get($key);
        return $val == $value;
    }
}
